package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.User;
import com.zhentao.service.ChatMessageService;
import com.zhentao.service.UserService;
import com.zhentao.vo.Result;
import com.zhentao.websocket.pojo.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/search")
public class SearchController {

    private static final Logger log = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private UserService userService;

    /**
     * 综合搜索接口
     * GET /api/search/all?keyword=xxx&type=all&userId=xxx
     */
    @GetMapping("/all")
    public Result<Map<String, Object>> searchAll(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "all") String type,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String username) {
        
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.fail("搜索关键词不能为空");
            }
            
            keyword = keyword.trim();
            Map<String, Object> result = new HashMap<>();
            
            // 根据搜索类型执行不同的搜索
            if ("all".equals(type) || "contacts".equals(type)) {
                // 搜索联系人
                List<User> contacts = searchContacts(keyword, userId);
                result.put("contacts", formatContactResults(contacts, userId));
            }
            
            if ("all".equals(type) || "groups".equals(type)) {
                // 搜索群聊（暂时返回空列表，后续可扩展）
                result.put("groups", new ArrayList<>());
            }
            
            if ("all".equals(type) || "messages".equals(type)) {
                // 搜索聊天记录
                List<ChatMessage> messages = searchMessages(keyword, userId, username);
                result.put("messages", formatMessageResults(messages, userId, username));
            }
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("搜索失败: " + e.getMessage());
        }
    }

    /**
     * 搜索聊天记录接口
     * GET /api/search/messages?keyword=xxx&userId=xxx&page=0&size=20
     */
    @GetMapping("/messages")
    public Result<Map<String, Object>> searchMessages(
            @RequestParam String keyword,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String username,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.fail("搜索关键词不能为空");
            }
            
            List<ChatMessage> messages = searchMessages(keyword.trim(), userId, username);
            List<Map<String, Object>> formattedMessages = formatMessageResults(messages, userId, username);
            
            // 分页处理
            int start = page * size;
            int end = Math.min(start + size, formattedMessages.size());
            List<Map<String, Object>> pagedMessages = start < formattedMessages.size() ? 
                formattedMessages.subList(start, end) : new ArrayList<>();
            
            Map<String, Object> result = new HashMap<>();
            result.put("messages", pagedMessages);
            result.put("page", page);
            result.put("size", size);
            result.put("total", formattedMessages.size());
            
            return Result.success(result);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("搜索聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 搜索联系人
     */
    private List<User> searchContacts(String keyword, Integer currentUserId) {
        List<User> users = new ArrayList<>();
        
        // 判断是否是手机号
        if (keyword.matches("^1[3-9]\\d{9}$")) {
            User user = userService.getOne(new QueryWrapper<User>()
                .eq("phone", keyword)
                .eq("status", 1));
            if (user != null) {
                users.add(user);
            }
        }
        
        // 根据用户名搜索
        List<User> usersByUsername = userService.list(new QueryWrapper<User>()
            .like("username", keyword)
            .eq("status", 1)
            .last("LIMIT 10"));
        users.addAll(usersByUsername);
        
        // 根据昵称搜索
        List<User> usersByNickname = userService.list(new QueryWrapper<User>()
            .like("nickname", keyword)
            .eq("status", 1)
            .last("LIMIT 10"));
        users.addAll(usersByNickname);
        
        // 去重并排除自己
        return users.stream()
            .distinct()
            .filter(user -> currentUserId == null || !user.getId().equals(Long.valueOf(currentUserId)))
            .limit(20)
            .collect(Collectors.toList());
    }

    /**
     * 搜索聊天记录
     */
    private List<ChatMessage> searchMessages(String keyword, Integer userId, String username) {
        return chatMessageService.searchMessagesByKeyword(keyword, userId, username);
    }

    /**
     * 格式化联系人搜索结果
     */
    private List<Map<String, Object>> formatContactResults(List<User> contacts, Integer currentUserId) {
        return contacts.stream().map(user -> {
            Map<String, Object> contact = new HashMap<>();
            contact.put("id", user.getId());
            contact.put("name", user.getUsername());
            contact.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
            contact.put("avatar", user.getAvatar() != null ? user.getAvatar() : 
                "https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3");
            contact.put("type", "private");
            contact.put("conversationId", generateConversationId(currentUserId, user.getId().intValue()));
            contact.put("lastMessage", "");
            contact.put("unreadCount", 0);
            return contact;
        }).collect(Collectors.toList());
    }

    /**
     * 格式化聊天记录搜索结果
     */
    private List<Map<String, Object>> formatMessageResults(List<ChatMessage> messages, Integer userId, String username) {
        return messages.stream().map(message -> {
            Map<String, Object> result = new HashMap<>();
            result.put("id", message.getId());
            result.put("content", message.getMessage());
            result.put("timestamp", message.getTimestamp());

            // 添加原始的 fromId 和 toId 字段
            result.put("fromId", message.getFromId());
            result.put("toId", message.getToId());

            // 根据当前用户ID判断消息方向，确定对话对象ID
            Integer conversationPartnerId;
            if (message.getFromId() != null && message.getFromId().equals(userId)) {
                // 当前用户是发送方，对话对象是接收方
                conversationPartnerId = message.getToId();
            } else {
                // 当前用户是接收方，对话对象是发送方
                conversationPartnerId = message.getFromId();
            }

            // 根据对话对象ID查询数据库获取最新的用户信息
            String conversationPartnerName = "未知用户";
            String conversationPartnerNickname = "未知用户";
            String conversationPartnerAvatar = "https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3";

            if (conversationPartnerId != null) {
                try {
                    User conversationPartner = userService.getOne(new QueryWrapper<User>()
                            .eq("id", Long.valueOf(conversationPartnerId))
                            .eq("status", 1)); // 只查询正常状态的用户

                    if (conversationPartner != null) {
                        conversationPartnerName = conversationPartner.getUsername();
                        conversationPartnerNickname = conversationPartner.getNickname() != null ?
                            conversationPartner.getNickname() : conversationPartner.getUsername();
                        if (conversationPartner.getAvatar() != null &&
                            !conversationPartner.getAvatar().isEmpty() &&
                            !"identity_verified".equals(conversationPartner.getAvatar())) {
                            conversationPartnerAvatar = conversationPartner.getAvatar();
                        }
                    }
                } catch (Exception e) {
                    log.warn("查询对话对象用户信息失败: userId={}, error={}", conversationPartnerId, e.getMessage());
                }
            }

            // 设置显示信息（显示对话对象的头像和昵称）
            result.put("senderName", conversationPartnerNickname);
            result.put("senderAvatar", conversationPartnerAvatar);

            // 设置对话对象信息（用于跳转）
            result.put("conversationPartnerName", conversationPartnerName);
            result.put("conversationPartnerNickname", conversationPartnerNickname);
            result.put("conversationPartnerAvatar", conversationPartnerAvatar);
            result.put("toUserId", conversationPartnerId);

            result.put("conversationName", "与 " + conversationPartnerNickname + " 的对话");
            result.put("conversationId", message.getConversationId());

            return result;
        }).collect(Collectors.toList());
    }

    /**
     * 生成会话ID
     */
    private String generateConversationId(Integer user1Id, Integer user2Id) {
        if (user1Id == null || user2Id == null) {
            return "";
        }
        return user1Id < user2Id ? user1Id + "_" + user2Id : user2Id + "_" + user1Id;
    }
}
